<template>
  <div v-if="!messageVisible" class="main-container">
    <div class="form-container">
      <el-form ref="formRef" :model="formModel" :rules="rules" @submit.prevent>
        <div class="container-title">AI智能出题</div>
        <el-form-item class="form-group" label="" prop="questionContent">
          <el-input v-model="formModel.questionContent" placeholder="请输入出题要求，如：关于人工智能如何发展？" type="textarea" rows="10" maxlength="500" show-word-limit />
        </el-form-item>
        <div class="container-title">
          <el-text>每次最多允许出题{{ questionCount }}道</el-text>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item class="form-group" label="单选题" prop="dansCount">
              <el-input-number v-model="formModel.danxCount" class="min-number" controls-position="right" :min="0" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="form-group" label="多选题" prop="duosCount">
              <el-input-number v-model="formModel.duoxCount" class="min-number" controls-position="right" :min="0" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="form-group" label="判断题" prop="pandCount">
              <el-input-number v-model="formModel.pandCount" class="min-number" controls-position="right" :min="0" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12"
            ><el-form-item class="form-group" label="填空题" prop="tiankCount">
              <el-input-number v-model="formModel.tiankCount" class="min-number" controls-position="right" :min="0" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="form-group" label="简答题" prop="jiansCount">
              <el-input-number v-model="formModel.jiandCount" class="min-number" controls-position="right" :min="0" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <div style="text-align: center">
          <div><el-text></el-text></div>
          <el-button type="primary" :loading="loading" @click="onSubmit()">AI出题</el-button>
        </div>
      </el-form>
    </div>
    <div style="border: 1px solid #eee"></div>
    <div class="page-container">
      <el-affix :offset="90">
        <div class="container-title">
          特别说明： <el-text>出题结果为AI自动生成的，需要自行确认是否正确。</el-text>
          <el-button type="success" :loading="loading" @click="handelQuestion">进入编辑</el-button>
        </div>
      </el-affix>
      <div class="question">{{ messages }}</div>
    </div>
  </div>
  <question v-if="messageVisible" :messages="messages" @callback="handelCallback" />
</template>

<script setup>
  import { onUnmounted, reactive, ref } from 'vue'
  import { ElMessage } from 'element-plus'
  import { questionApi } from '@/api/question.js'
  import Question from './Question.vue'

  // 每次出题限额，默认10道
  const questionCount = ref(10)

  // 进入编辑
  const messageVisible = ref(false)
  const handelQuestion = () => {
    messageVisible.value = true
  }

  // 回调处理
  const handelCallback = () => {
    messageVisible.value = false
    messages.value = ''
    Object.assign(formModel, formDefault)
  }

  // AI出题
  let questionAiCompletions = undefined
  const messages = ref('')

  // 校验规则
  const formRef = ref()
  const rules = {
    questionContent: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
  // 表单
  const loading = ref(false) // 加载进度状态
  const formDefault = {
    questionContent: '',
    danxCount: 0,
    duoxCount: 0,
    pandCount: 0,
    tiankCount: 0,
    jiandCount: 0
  }
  const formModel = reactive({ ...formDefault })
  const onSubmit = async () => {
    // 校验
    const valid = await formRef.value.validate()
    if (!valid) return
    if (loading.value === true) {
      ElMessage.warning('正在处理···')
      return
    }
    // 统计题目数量不超20到
    if (formModel.danxCount + formModel.duoxCount + formModel.pandCount + formModel.tiankCount + formModel.jiandCount > questionCount.value) {
      ElMessage.warning('题目数量不能超过' + questionCount.value + '道')
      return
    }

    if (formModel.questionContent) {
      loading.value = true
      const res = await questionApi.questionAiCreate(formModel)
      questionAiCompletions = await questionApi.questionAiCompletions({ aiToken: res })
      if (questionAiCompletions) {
        messages.value = ''
        questionAiCompletions.onmessage = (message) => {
          if (message.data.includes('[DONE]')) {
            loading.value = false
            questionAiCompletions.close()
            return
          }
          if (message.data.includes('[ERROR]')) {
            ElMessage.error('AI出题失败，请稍后重试')
            loading.value = false
            questionAiCompletions.close()
            return
          }
          // 输出内容
          if (!loading.value) {
            loading.value = true
          }
          messages.value = messages.value + message.data
        }
        questionAiCompletions.onerror = (e) => {
          console.error(e)
          loading.value = false
          questionAiCompletions.close()
        }
      }
    }
  }

  onUnmounted(() => {
    if (questionAiCompletions) {
      questionAiCompletions.close()
    }
  })
</script>
<style lang="scss" scoped>
  .main-container {
    display: flex;
    flex-direction: row;
    gap: 20px;
  }
  .form-container {
    width: 380px;
    overflow: auto;
  }
  .page-container {
    flex: 1;
    overflow: auto;

    .container-title {
      background-color: #ffffff;
    }

    .question {
      white-space: pre-wrap;
      font-size: 14px;
      line-height: 2;
    }
  }
</style>
